import React, { useState, useEffect } from 'react';
import useStore from '../../../components/useStore';
import { 
  Form, 
  Input, 
  Button, 
  Card, 
  Typography, 
  Select, 
  Space, 
  message, 
  Spin 
} from 'antd';
import { 
  SaveOutlined, 
  ArrowLeftOutlined 
} from '@ant-design/icons';
import request from '../../../untils/request';

const { Option } = Select;
const { Title } = Typography;

const AddBom = () => {
  const { collapsed } = useStore();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [parentOptions, setParentOptions] = useState([]); // 父级BOM选项

  // 获取所有可用的父级BOM（顶级BOM）
  const fetchParentBoms = () => {
    request("/admin/bom/getBom", {
      method: "POST",
      body: {
        pageSize: 1000, // 获取足够多的顶级BOM作为父级选项
        offset: 0,
        topLevel: true
      }
    }).then((res) => {
      if (res.code === 200) {
        const options = res.data?.list?.map(item => ({
          value: item.number,
          label: `${item.number} - ${item.productName}`
        })) || [];
        setParentOptions(options);
      }
    }).catch(error => {
      message.error(`获取父级BOM列表失败: ${error.message}`);
    });
  };

  // 组件挂载时获取父级BOM列表
  useEffect(() => {
    fetchParentBoms();
  }, []);

  // 提交表单
  const handleSubmit = () => {
    form.validateFields().then(values => {
      setLoading(true);
      // 调用新增BOM接口
      request("/admin/bom/addBom", {
        method: "POST",
        body: {
          number: values.number,
          parentNumber: values.parentNumber || '',
          productName: values.productName,
          specificationAndModel: values.specificationAndModel || ''
        }
      }).then(res => {
        setLoading(false);
        if (res.code === 200) {
          message.success("BOM新增成功");
          // 重置表单
          form.resetFields();
          // 可以在这里添加跳转逻辑，比如返回列表页
        } else {
          message.error(`新增失败: ${res.msg || '未知错误'}`);
        }
      }).catch(error => {
        setLoading(false);
        message.error(`请求失败: ${error.message || '网络错误'}`);
      });
    }).catch(info => {
      message.warning('表单验证失败，请检查输入');
    });
  };

  // 取消操作
  const handleCancel = () => {
    // 返回上一页或关闭当前页面的逻辑
    // 这里可以根据你的路由方式进行调整
    window.history.back();
  };

  return (
    <div style={{    
      height: "94%", 
      backgroundColor: '#F1F1F1',
      right: "1%",
      top: "4vh",
      overflow: "auto",
      width: collapsed ? "94%" : "84%", 
      position: "absolute",  
      transition: "width 0.3s ease"
    }}>
      <Card style={{ 
        margin: '20px', 
        border: 0, 
        boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)' 
      }}>
        <Title level={4} style={{ marginBottom: 20 }}>新增BOM</Title>
        
        <Spin spinning={loading}>
          <Form
            form={form}
            layout="vertical"
            initialValues={{ parentNumber: '' }}
          >
            <Form.Item
              name="number"
              label="产品编号"
              rules={[
                { required: true, message: '请输入产品编号' },
                { max: 50, message: '产品编号长度不能超过50个字符' }
              ]}
            >
              <Input placeholder="请输入产品编号" />
            </Form.Item>

            <Form.Item
              name="parentNumber"
              label="父级编号"
              tooltip="选择父级BOM（可选，最多支持两层）"
            >
              <Select 
                placeholder="请选择父级BOM（可选）" 
                style={{ width: '100%' }}
                allowClear
              >
                {parentOptions.map(option => (
                  <Option key={option.value} value={option.value}>
                    {option.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="productName"
              label="产品品名"
              rules={[
                { required: true, message: '请输入产品品名' },
                { max: 100, message: '产品品名长度不能超过100个字符' }
              ]}
            >
              <Input placeholder="请输入产品品名" />
            </Form.Item>

            <Form.Item
              name="specificationAndModel"
              label="产品规格"
              rules={[
                { max: 200, message: '产品规格长度不能超过200个字符' }
              ]}
            >
              <Input placeholder="请输入产品规格（可选）" />
            </Form.Item>

            <Form.Item style={{ marginTop: 30 }}>
              <Space size="middle">
                <Button 
                  type="primary" 
                  icon={<SaveOutlined />} 
                  onClick={handleSubmit}
                  loading={loading}
                >
                  保存
                </Button>
                <Button 
                  icon={<ArrowLeftOutlined />} 
                  onClick={handleCancel}
                >
                  取消
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Spin>
      </Card>
    </div>
  );
};

export default AddBom;
